<template>
  <div class="page_root">
    <var-card>
      <div class="form_wrapper">
        <var-form labvar-width="100px" labvar-position="left">
          <div v-if="!init">
            <var-form-item label="旧密码:">
              <var-input
                type="password"
                show-password
                v-model.trim="form.old"
              />
            </var-form-item>
          </div>
          <var-form-item label="新密码:">
            <var-input type="password" show-password v-model.trim="form.neo" />
          </var-form-item>
          <var-form-item label="重复新密码:">
            <var-input
              type="password"
              show-password
              v-model.trim="form.confirm"
            />
          </var-form-item>
        </var-form>
        <var-button @click="submit" primary>提交</var-button>
      </div>
    </var-card>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import * as http from "./api";
import encode from "@/utils/encryption";
export default {
  name: "password-edit",
  data() {
    return {
      init: false,
      form: {
        old: "",
        neo: "",
        confirm: "",
      },
    };
  },
  computed: {
    ...mapGetters({
      userInfo: "user",
    }),
  },
  mounted() {
    if (!this.userInfo.active) {
      this.$message.error("请重置管理员密码");
      this.init = true;
    }
  },
  methods: {
    async submit() {
      if (!this.init && this.form.old === "") {
        this.$message.error("旧密码不能为空");
        return;
      }
      if (this.form.neo === "") {
        this.$message.error("新密码不能为空");
        return;
      }

      if (
        !/[A-Z]/g.test(this.form.neo) ||
        !/[a-z]/g.test(this.form.neo) ||
        !/\d/g.test(this.form.neo) ||
        !/^[A-Za-z]/g.test(this.form.neo) ||
        this.form.neo.length < 8
      ) {
        this.$message.error(
          "密码太过简单，要求密码为包含大写字母、小写字母、数字，且以字母开头的8位以上字符"
        );
        return;
      }
      if (this.form.confirm === "") {
        this.$message.error("重复密码不能为空");
        return;
      }
      if (this.form.neo !== this.form.confirm) {
        this.$message.error("两次密码输入不一致");
        return;
      }
      try {
        const res = await http.updatePassword({
          old: encode(this.form.old),
          neo: encode(this.form.neo),
          confirm: encode(this.form.confirm),
        });
        if (res.code !== 200) {
          this.$message.error("密码设置失败，请稍后重试");
          return;
        }
        this.form = {
          old: "",
          neo: "",
          confirm: "",
        };
        this.$message.success("密码修改成功");
        this.init = false;
        this.$store.commit("user/SET_ACTIVE", true);
      } catch (e) {
        console.log(e);
        this.$message.error("密码设置失败，请稍后重试");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.page_root {
  .form_wrapper {
    max-width: 600px;
  }
}
</style>
